package org.example.bigwork.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.bigwork.common.Result;
import org.example.bigwork.entity.Attachment;
import org.example.bigwork.entity.Student;
import org.example.bigwork.entity.Task;
import org.example.bigwork.service.AttachmentService;
import org.example.bigwork.service.StudentService;
import org.example.bigwork.service.TaskService;
import org.example.bigwork.util.TaskUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/api/student")
public class StudentTaskController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private AttachmentService attachmentService;

    private final String UPLOAD_DIR = "uploads/";


    /**
     * 获取学生信息
     */
    @GetMapping("/{studentId}")
    public Result<Student> getStudentInfo(@PathVariable String studentId) {
        log.info("获取学生信息");
        Student student = studentService.getStudentById(studentId);
        if (student != null) {
            return Result.success(student);
        } else {
            return Result.error("学生ID不能为空");
        }
    }

    /**
     * 获取学生的任务列表
     */
    @GetMapping("/tasks/{studentId}")
    public Result<List<Task>> getStudentTasks(@PathVariable String studentId) {
        log.info("获取学生的任务列表");
        List<Task> tasks = studentService.getStudentTasks(studentId);
        return Result.success(tasks);
    }

    /**
     * 获取学生的任务列表（按截止时间排序）
     */
    @GetMapping("/tasks/sorted-by-deadline/{studentId}")
    public Result<List<Task>> getStudentTasksSortedByDeadline(@PathVariable String studentId) {
        log.info("获取学生的任务列表（按截止时间排序）");
        List<Task> tasks = studentService.getStudentTasks(studentId);
        return Result.success(TaskUtils.sortByDeadline(tasks));
    }

    /**
     * 获取学生的任务列表（按工作量排序）
     */
    @GetMapping("/tasks/sorted-by-workload/{studentId}")
    public Result<List<Task>> getStudentTasksSortedByWorkload(@PathVariable String studentId) {
        log.info("获取学生的任务列表（按工作量排序）");
        List<Task> tasks = studentService.getStudentTasks(studentId);
        return Result.success(TaskUtils.sortByWorkload(tasks));
    }

    /**
     * 获取学生的未完成任务
     */
    @GetMapping("/tasks/incomplete/{studentId}")
    public Result<List<Task>> getStudentIncompleteTasks(@PathVariable String studentId) {
        log.info("获取学生的未完成任务");
        List<Task> tasks = studentService.getStudentTasks(studentId);
        return Result.success(TaskUtils.filterByCompletionStatus(tasks, "未完成"));
    }

    /**
     * 获取学生的即将到期任务（7天内）
     */
    @GetMapping("/tasks/upcoming/{studentId}")
    public Result<List<Task>> getStudentUpcomingTasks(@PathVariable String studentId) {
        log.info("获取学生的即将到期任务（7天内）");
        List<Task> tasks = studentService.getStudentTasks(studentId);
        return Result.success(TaskUtils.getUpcomingDeadlineTasks(tasks, 7));
    }

    /**
     * 学生领用任务
     */
    @PostMapping("/claim-task/{taskId}/{studentId}")
    public Result<Map<String, Object>> claimTask(@PathVariable String studentId, @PathVariable String taskId) {
        log.info("学生领用任务");
        boolean success = studentService.claimTask(studentId, taskId);
        Map<String, Object> response = new HashMap<>();
        if (success) {
            response.put("success", true);
            response.put("message", "任务领用成功");
        } else {
            response.put("success", false);
            response.put("message", "任务领用失败，可能任务已被领用或不存在");
        }

        return Result.success(response);
    }


    /**
     * 学生取消领用任务
     */
    @PostMapping("/cancel-task/{taskId}/{studentId}")
    public Result<Map<String, Object>> cancelTask(@PathVariable String studentId, @PathVariable String taskId) {
        log.info("学生取消领用任务");
        boolean success = studentService.cancelTask(studentId, taskId);
        Map<String, Object> response = new HashMap<>();
        if (success) {
            response.put("success", true);
            response.put("message", "取消领用成功");
        } else {
            response.put("success", false);
            response.put("message", "取消领用失败，可能任务不存在或未被该学生领用");
        }

        return Result.success(response);
    }


    /**
     * 学生完成任务
     */
    @PostMapping("/complete-task/{taskId}/{studentId}")
    public Result<Map<String, Object>> completeTask(@PathVariable String studentId, @PathVariable String taskId) {
        log.info("学生完成任务");
        // 检查任务是否被该学生领用
        if (studentService.getTaskMap(studentId).containsKey(taskId)) {
            boolean success = taskService.updateTaskCompletionStatus(taskId, "已完成");

            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("success", true);
                response.put("message", "任务已标记为完成");
            } else {
                response.put("success", false);
                response.put("message", "更新任务状态失败");
            }

            return Result.success(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "该任务不属于此学生");
            return Result.success(response);
        }
    }


    /**
     * 上传任务附件
     */
    @PostMapping("/task/upload/{taskId}/{studentId}")
    public Result<Map<String, Object>> uploadAttachment(
            @PathVariable String studentId,
            @PathVariable String taskId,
            @RequestParam("file") MultipartFile file) {
        log.info("上传任务附件");

        Map<String, Object> response = new HashMap<>();

        // 检查任务是否被该学生领用
        if (!studentService.getTaskMap(studentId).containsKey(taskId)) {
            response.put("success", false);
            response.put("message", "该任务不属于此学生");
            return Result.success(response);
        }

        try {
            // 创建上传目录
            File uploadDir = new File(UPLOAD_DIR + taskId);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;
            String filePath = UPLOAD_DIR + taskId + "/" + newFilename;

            // 保存文件
            Path path = Paths.get(filePath);
            Files.write(path, file.getBytes());

            // 创建附件记录
            Attachment attachment = Attachment.builder()
                    .fileName(originalFilename)
                    .filePath(filePath)
                    .uploadTime(LocalDateTime.now())
                    .taskId(taskId)
                    .build();

            boolean success = attachmentService.addAttachment(attachment);

            if (success) {
                response.put("success", true);
                response.put("message", "附件上传成功");
                response.put("fileName", originalFilename);
                response.put("filePath", filePath);
            } else {
                response.put("success", false);
                response.put("message", "附件记录保存失败");
            }

        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "附件上传失败: " + e.getMessage());
        }

        return Result.success(response);
    }


    /**
     * 获取任务附件列表
     */
    @GetMapping("/task/attachments/{taskId}")
    public Result<List<Attachment>> getTaskAttachments(@PathVariable String taskId) {
        log.info("获取任务附件列表");
        List<Attachment> attachments = attachmentService.getAttachmentsByTaskId(taskId);
        return Result.success(attachments);
    }


    /**
     * 删除任务附件
     */
    @DeleteMapping("/attachment/{attachmentId}/{studentId}")
    public Result<Map<String, Object>> deleteAttachment(
            @PathVariable String studentId,
            @PathVariable Integer attachmentId) {
        log.info("删除任务附件");

        Map<String, Object> response = new HashMap<>();

        boolean success = attachmentService.deleteAttachment(attachmentId);

        if (success) {
            response.put("success", true);
            response.put("message", "附件删除成功");
        } else {
            response.put("success", false);
            response.put("message", "附件删除失败");
        }

        return Result.success(response);
    }
    /**
     * 获取可领用的任务列表
     */
    @GetMapping("/available-tasks")
    public Result<List<Task>> getAvailableTasks() {
        log.info("获取可领用的任务列表");
        List<Task> tasks = taskService.getTasksByClaimStatus("未领用");
        return Result.success(tasks);
    }

    /**
     * 预览文件
     */
    @GetMapping("/preview/{taskId}/{fileName}")
    public ResponseEntity<byte[]> previewFile(
            @PathVariable String taskId,
            @PathVariable String fileName) {
        try {
            String filePath = UPLOAD_DIR + taskId + "/" + fileName;
            Path path = Paths.get(filePath);
            byte[] fileContent = Files.readAllBytes(path);
            
            // 根据文件类型设置Content-Type
            String contentType = Files.probeContentType(path);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            
            return ResponseEntity.ok()
                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
                    .body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.notFound().build();
        }
    }
} 